<?php
namespace Admin\Controller;
use Think\Controller;
use Org\Util\Rbac;
use Think\Log;
use Common\Api\SystemApi;

class CommonController extends Controller {

	function _initialize($dwz_db_name = '') {

		if (!isset($_SESSION[C('USER_AUTH_KEY')])) {

			$this->redirect('Public/login');
		}
        $input= new \OT\Input();
       
       $input->noGPC();
	    /* 读取数据库中的配置 */
        $this->readconfig();
      
        //dump(C('CONFIG_GROUP_LIST'));
       
	   if($_SESSION[C('USER_AUTH_KEY')] != 1 && C('ADMIN_ALLOW_IP')){
            // 检查IP地址访问
            if(!in_array(get_client_ip(),explode(',',C('ADMIN_ALLOW_IP')))){
                $this->error('403:禁止访问');
            }
        }

		// 用户权限检查
		if (C('USER_AUTH_ON') && !in_array(CONTROLLER_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
			
			if (!RBAC::AccessDecision()) {

				//检查认证识别号
				if (!$_SESSION[C('USER_AUTH_KEY')]) {
					//跳转到认证网关
					redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
				}
				// 没有权限 抛出错误
				if (C('RBAC_ERROR_PAGE')) {
					// 定义权限错误页面
					redirect(C('RBAC_ERROR_PAGE'));
				} else {
					if (C('GUEST_AUTH_ON')) {
						$this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
					}
					// 提示错误信息
					// $this->mtReturn(300,'对不起，您的权限不足！请不要越级操作！');
				}
			}
		}
		$dwz_db_name = $dwz_db_name ? $dwz_db_name : strtolower(CONTROLLER_NAME);
		$this->dbname=$dwz_db_name;//取得当前操作的数据表的名称

	}
	public function readconfig(){
		
		 /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置
        return;
	}
	
	public function xlsout($filename='数据表',$headArr,$list){
			
		//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Writer.Excel5");
		import("Org.Util.PHPExcel.IOFactory.php");
		$this->getExcel($filename,$headArr,$list);
	}
	public function xlsin(){
			
		//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("Org.Util.PHPExcel");
		//要导入的xls文件，位于根目录下的Public文件夹
		$filename="./Public/1.xls";
		//创建PHPExcel对象，注意，不能少了\
		$PHPExcel=new \PHPExcel();
		//如果excel文件后缀名为.xls，导入这个类
		import("Org.Util.PHPExcel.Reader.Excel5");
		//如果excel文件后缀名为.xlsx，导入这下类
		//import("Org.Util.PHPExcel.Reader.Excel2007");
		//$PHPReader=new \PHPExcel_Reader_Excel2007();

		$PHPReader=new \PHPExcel_Reader_Excel5();
		//载入文件
		$PHPExcel=$PHPReader->load($filename);
		//获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
		$currentSheet=$PHPExcel->getSheet(0);
		//获取总列数
		$allColumn=$currentSheet->getHighestColumn();
		//获取总行数
		$allRow=$currentSheet->getHighestRow();
		//循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
		for($currentRow=1;$currentRow<=$allRow;$currentRow++){
			//从哪列开始，A表示第一列
			for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
				//数据坐标
				$address=$currentColumn.$currentRow;
				//读取到的数据，保存到数组$arr中
				$arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
			}

		}
			
	}
	public	function getExcel($fileName,$headArr,$data){
		//对数据进行检验
		if(empty($data) || !is_array($data)){
			die("data must be a array");
		}
		//检查文件名
		if(empty($fileName)){
			exit;
		}

		$date = date("Y_m_d",time());
		$fileName .= "_{$date}.xls";


		//创建PHPExcel对象，注意，不能少了\
		$objPHPExcel = new \PHPExcel();
		$objProps = $objPHPExcel->getProperties();
			
		//设置表头
		$key = ord("A");
		foreach($headArr as $v){
			$colum = chr($key);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
			$key += 1;
		}

		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();


		//设置为文本格式
		foreach($data as $key => $rows){ //行写入
			$span = ord("A");
			foreach($rows as $keyName=>$value){// 列写入
				$j = chr($span);

				$objActSheet->setCellValueExplicit($j.$column, $value);
				$span++;
			}
			$column++;
		}

		$fileName = iconv("utf-8", "gb2312", $fileName);
		//重命名表
		// $objPHPExcel->getActiveSheet()->setTitle('test');
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=\"$fileName\"");
		header('Cache-Control: max-age=0');

		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); //文件通过浏览器下载
		exit;
	}
	//拿到等级为2的用户id
	public function get_top_parentids($p_id){
        $arr = M('user')->where(array('id'=>$p_id))->find();
        if($arr['dengji'] != 2) {
            return $this->get_top_parentids($arr['parent_id']);
        }
        return $arr['id'];
    }

	protected function _list($model, $map, $asc = false) {
        $curre_user_id = $_SESSION['zs_admin']['userid'];
		$ausers = M('user')->where(array('id'=>$curre_user_id))->find();//当前用户
		
		if ($curre_user_id == 1) {
			$ausers['smssum'] = M('config')->where(array('name'=>'WEB_SMS_NUM'))->getField('value');//总的条数
			$ausers['count'] = M('user')->sum('smssum');//分出去的
		}else{
			if ($ausers['dengji'] == 2) {
				$san_sum = M('user')->where(array('parent_id'=>$ausers['id']))->sum('smssum');
				$san = M('user')->field('id')->where(array('parent_id'=>$ausers['id']))->select();
				foreach ($san as $key => $val) {
					$si_data += M('user')->where(array('parent_id'=>$val['id']))->sum('smssum');
				}
				$count = $ausers['smssum'];
				$ausers['smssum'] = $ausers['smssum'] + $san_sum + $si_data;
				$ausers['count'] = $ausers['smssum'] - $count;
			}
			if ($ausers['dengji'] == 3) {
				$count = $ausers['smssum'];
				$si = M('user')->where(array('parent_id'=>$ausers['id']))->sum('smssum');
				$ausers['smssum'] = $ausers['smssum'] + $si;
				$ausers['count'] = $ausers['smssum'] - $count;
			}
		}
		// echo "<pre>";
  //           print_r($ausers);die;
  //           echo "</pre>";
		//排序字段 默认为主键名
		if (isset($_REQUEST ['orderField'])) {
			$order = $_REQUEST ['orderField'];
		}
		if($order=='') {
			$order = $model->getPk();

		}
			
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset($_REQUEST ['orderDirection'])) {
			$sort = $_REQUEST ['orderDirection'];
		}
		if($sort=='') {
			$sort = $asc ? 'asc' : 'desc';

		}

		if($curre_user_id != 1){
			if(($this->dbname) != "user"){
				if(($this->dbname) == "kahao"){
					if ($ausers['dengji'] == 2) {//二级
						$map['user_id'] = $curre_user_id;
					}
					if ($ausers['dengji'] == 3) {//三级
						$map['san_id'] = $curre_user_id;
					}
					if ($ausers['dengji'] == 4) {//四级
						$map['si_id'] = $curre_user_id;
					}

				}elseif(($this->dbname) == "article"){

					if ($ausers['dengji'] == 2) {//二级
						$map['user_id'] = $curre_user_id;
					}
					if ($ausers['dengji'] == 3) {//三级
						$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
					}
					if ($ausers['dengji'] == 4) {//四级
						$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
					}
					// print_r($ausers['dengji']);die;
			  //   	$map['user_id'] = $curre_user_id;
				}else{
					$map['user_id'] = $curre_user_id;
				}
			}else{
				if (empty($map['status'])) {//表示查询权限的表
					$map['parent_id'] = $curre_user_id;
				}
			}
	    }else{
	    	//总后台的用户
	    	if(($this->dbname) == "user"){
	    		if (empty($map['status'])) {//表示查询权限的表
					$map['parent_id'] = 1;
				}
	    		
	    	}
	    }
	    //接收记录
	    if(($this->dbname)=="shousms"){
	    	if ($ausers['dengji'] == 3 || $ausers['dengji'] == 4) {
	    		$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
	    	}
	    }
	    if ($this->dbname == "codelist") {
	    	
	    	if ($ausers['dengji'] == 2) {
	    		$map['user_id'] = $ausers['id'];
	    	}
	    	if ($ausers['dengji'] == 3) {
	    		$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
	    	}
	    	if ($ausers['dengji'] == 4) {
	    		$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
	    	}
	    }
		//取得满足条件的记录数
		$count = $model->where($map)->count();
		if ($count > 0) {
			$p = new \Think\Page($count, $listRows);
			//分页查询数据
			$numPerPage = empty($_REQUEST['numPerPage']) ? C('PAGE_LISTROWS') : $_REQUEST['numPerPage'];

			if ($this->dbname == 'kahao' || $this->dbname == 'article') {
				//卡号列表数据条数
				$numPerPage = 100;
			}
			
			//上面的获得每页显示的数据条数
			// dump("`" . $order . "` " . $sort);
			//分页查询数据
            
			$voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($numPerPage)->page($_REQUEST[C('VAR_PAGE')])->select();
			if(($this->dbname)=="user"){
				if ($curre_user_id == 1) {
					foreach ($voList as $key => $val) {
						if ($val['dengji'] == 2) {
							if ($val['smssum'] == 0) {
								$san_list = M('user')->where(array('parent_id'=>$val['id']))->select();
								foreach ($san_list as $k => $v) {
									$san_c += $v['smssum'];
									$si_list = M('user')->where(array('parent_id'=>$v['id']))->select();
									foreach ($si_list as $k1 => $v1) {
										$si_c += $v1['smssum'];
									}
								}
								$voList[$key]['smssums'] = $san_c + $si_c;
								
							}else{
								$voList[$key]['smssums'] = $val['smssum'];
							}
						}
						
					}
				}
				$user = M('user')->where(array('id'=>$curre_user_id))->find();
				if ($user['dengji'] == 2) {//登录的二级用户
					foreach ($voList as $key => $val) {
						if ($val['smssum'] == 0) {
							$si_list = M('user')->where(array('parent_id'=>$val['id']))->select();
							foreach ($si_list as $k1 => $v1) {
								$si_c += $v1['smssum'];
								$voList[$key]['smssums'] = $si_c;
							}
						}else{
							$voList[$key]['smssums'] = $val['smssum'];
						}
					
					}
				}
				if ($user['dengji'] == 3) {
					foreach ($voList as $key => $val) {
						$voList[$key]['smssums'] = $val['smssum'];
					}					
				}
				

			}
			// print_r($si_c);die;
			///目的码记录
			if(($this->dbname)=="codelist"){
          //       foreach ($voList as $key => $val) {
		        //     $voList[$key]['nickname'] = M('user')->where(array('id'=>$val['user_id']))->getField('nickname');
		        // }
		        
		        if ($ausers['dengji'] == 2) {
		        	$map['user_id'] = $ausers['id'];
		        }
		        if ($ausers['dengji'] == 3) {
		        	$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
		        }
		        if ($ausers['dengji'] == 4) {
		        	$map['user_id'] = $this->get_top_parentids($ausers['parent_id']);
		        }
		        
		        $voList = M('codelist')->where($map)->order('id desc')->limit($numPerPage)->page($_REQUEST[C('VAR_PAGE')])->select();
		        foreach ($voList as $key => $val) {
		        	$voList[$key]['code'] = explode(',',$val['code']);
		        }
		        foreach ($voList as $key => $val) {
		        	$voList[$key]['nickname'] = M('user')->where(array('id'=>$val['user_id']))->getField('nickname');
		        	foreach ($val['code'] as $k => $va) {
		        	 	$voList[$key]['code'][$k] = M('article')->where("id=".$va)->order('id desc')->limit($numPerPage)->page($_REQUEST[C('VAR_PAGE')])->find();
			        }
		        }
			}
			//卡号列表
			if(($this->dbname)=="kahao"){
			    // $kauser = M('user')->field('id,nickname')->where('id != 1')->select();

			    $kauser = M('user')->field('id,nickname')->where(array('parent_id'=>$curre_user_id))->select();
			    $this->assign('kauser', $kauser);
				if($curre_user_id != 1){
				    $map['user_id'] =  $curre_user_id;
			    }

			    foreach ($voList as $key => $val) {
	                $voList[$key]['nickname'] = M('user')->where(array('id'=>$val['user_id']))->getField('nickname');//二级
	                $voList[$key]['sanname'] = M('user')->where(array('id'=>$val['san_id']))->getField('nickname');//三级
	                $voList[$key]['siname'] = M('user')->where(array('id'=>$val['si_id']))->getField('nickname');//四级
	                $voList[$key]['codeNo'] = M('article')->where(array('user_id'=>$val['user_id']))->getField('codeNo');//目的码
	                $voList[$key]['fa_state'] = M('fasms')->where(array('mobile'=>$val['mobile']))->getField('fa_state');//发送状态
	            }

			}
			//目的码管理
			if(($this->dbname)=="article"){
			    $kauser = M('user')->field('id,nickname')->where(array('parent_id'=>$curre_user_id))->select();
			    $this->assign('kauser', $kauser);
				if($curre_user_id != 1){
				    $map['user_id'] =  $curre_user_id;
			    }
			}
			//发送记录
			if(($this->dbname)=="fasms"){
                foreach ($voList as $key => $val) {
		            $voList[$key]['user_name'] = M('user')->where(array('id'=>$val['user_id']))->getField('nickname');
		        }
			}
			///接收记录
		    
			if(($this->dbname)=="shousms"){
                foreach ($voList as $key => $val) {
		            $voList[$key]['user_name'] = M('user')->where(array('id'=>$val['user_id']))->getField('nickname');
					if ($ausers['dengji'] == 3) {
						if ($ausers['id'] != M('kahao')->where(array('mobile'=>$val['mobile']))->getField('san_id')) {
							unset($voList[$key]);
						}
					}
					if ($ausers['dengji'] == 4) {
						if ($ausers['id'] != M('kahao')->where(array('mobile'=>$val['mobile']))->getField('si_id')) {
							unset($voList[$key]);
						}
					}
		        }
			}
    
			//分页跳转的时候保证查询条件
			foreach ($map as $key => $val) {
				if (!is_array($val)) {
					$p->parameter .= "$key=" . urlencode($val) . "&";
				}
			}

			//分页显示
			$page = $p->show();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			
		   if( method_exists($this, '_after_list')){
				
				$voList=$this->_after_list($voList);
			}

			/*统计二级用户的短信总条数*/
			// echo "<pre>";
			// print_r($voList);
			// echo "</pre>";
			//模板赋值显示
			$this->assign("map", $map);
			$this->assign('list', $voList);
			// $this->assign('ausers', $ausers);
			
			
			$this->assign('sort', $sort);
			$this->assign('order', $order);
			$this->assign('sortImg', $sortImg);
			$this->assign('sortType', $sortAlt);
			$this->assign("page", $page);
		}

		$this->assign('ausers', $ausers);	
		$this->assign('totalCount', $count);//数据总数
		$this->assign('currentPage', !empty($_REQUEST[C('VAR_PAGE')]) ? $_REQUEST[C('VAR_PAGE')] : 1);//当前的页数，默认为1
		$this->assign('numPerPage', $numPerPage); //每页显示多少条
		
		
		
			cookie('_currentUrl_', __SELF__);
		
		
		return;
	}

	/*post curl */
    public function RequestHttp($url){
        /* $url = "http://api.e114.xin/m2m_ec/query.do?user_id=miaoyue&access_number=1410331155200&sign=69261F8F5AA3C91B0B6806612018532C646B079B68A86AC0C1F669AA1AB5CD61D54FC8590DB4FBE5A052D333E0881BD2014278DB619743B89191E7314D0515529DA4295AB49E3D744E7C805C1B980BD9E4B6307D6DA31204704763269F2AC6B0A5DD546D5360A2642118568CDC4C5F3B&passWord=A301AFB6BF63307F3C1B159174BA6F47B829A2BF80005B50AB7FF0A286F73444&method=disabledNumber&orderTypeId=20";*/

        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

	public function index() {
        /*卡号管理*/
        if($this->dbname == "card") {
            /*查询没有调用查询接口的数据*/
            $cards = M('card');
            $yunying = M('yunying');
            $jiekou = M('jiekou');
            /*查询电信运营数据*/
            $dx_card = $cards->where(array('number' => 0, 'yunying_id' => 4))->select();
            if($dx_card){
                $data = $yunying->where(array('id' => 4))->find();
                foreach ($dx_card as $car) {
                    /*获取接口地址*/

                    $url = $jiekou->where(array('yunying_id' => 4, 'name' => '查询'))->getField('content');
                    set_time_limit(0);
                    header("Content-type:text/html;charset=utf-8");
                    $user_id = $data['username'];        //用户名
                    $password = $data['password'];//密码
                    $method = "queryPakage";  //接口名-套餐使用量查询 ADD DEL
                    $arr = array($car['card_id'], $user_id, $password, $method);//加密数组，数组所需参数根据对应的接口文档
                    $key1 = $data['key1'];
                    $key2 = $data['key2'];
                    $key3 = $data['key3'];
                    $des = new SystemApi(); //加密工具类实例化
                    $arrOrder = $des->naturalOrdering($arr); //加密数组元素排序
                    $sign = $des->strEnc($arrOrder, $key1, $key2, $key3);
                    $passwords = $des->strEnc($password, $key1, $key2, $key3);
                    $time = time();
                    $urls = $url . "?user_id=" . $user_id . "&access_number=" . $car['card_id'] . "&sign=" . $sign . "&passWord=" . $passwords . "&method=queryPakage";
                    $xml = $this->RequestHttp($urls);
                    $xmlTag = array(
                        'ACCU_NAME',
                        'CUMULATION_ALREADY',
                        'CUMULATION_LEFT',
                        'CUMULATION_TOTAL',
                        'END_TIME',
                        'OFFER_ID',
                        'OFFER_NAME',
                        'START_TIME',
                        'UNIT_NAME',
                        'OFFER_TYPE',
                        'IRESULT',
                        'GROUP_TRANSACTIONID',
                        'number'
                    );
                    $arr = array();
                    foreach ($xmlTag as $x) {
                        preg_match_all("/<" . $x . ">.*<\/" . $x . ">/", $xml, $temp);
                        $arr[] = $temp[0];
                    }
                    $data = array();
                    foreach ($arr as $key => $value) {
                        foreach ($value as $k => $v) {
                            $a = explode($xmlTag[$key] . '>', $v);
                            $v = substr($a[1], 0, strlen($a[1]) - 2);
                            $data[$k][$xmlTag[$key]] = $v;
                        }
                    }
                    $new_data['accu_name'] = $data[0]['ACCU_NAME'];
                    $new_data['cumulation_already'] = $data[0]['CUMULATION_ALREADY'];
                    $new_data['cumulation_left'] = $data[0]['CUMULATION_LEFT'];
                    $new_data['cumulation_total'] = $data[0]['CUMULATION_TOTAL'];
                    $new_data['end_time'] = $data[0]['END_TIME'];
                    $new_data['offer_id'] = $data[0]['OFFER_ID'];
                    $new_data['offer_name'] = $data[0]['OFFER_NAME'];
                    $new_data['start_time'] = $data[0]['START_TIME'];
                    $new_data['unit_name'] = $data[0]['UNIT_NAME'];
                    $new_data['offer_type'] = $data[0]['OFFER_TYPE'];
                    $new_data['group_transactionid'] = $data[0]['GROUP_TRANSACTIONID'];
                    $new_data['number'] = $data[0]['number'];
                    $res = $cards->where(array('card_id' => $data[0]['number']))->save($new_data);
                }
            }
            /*查询移动接口*/
            $yd_card = $cards->where(array('yunying_id' => 2))->select();
            $url_yd = $jiekou->where(array('yunying_id' => 2, 'name' => '卡状态查询'))->getField('content');
        /*   if($yd_card){
                //查询卡状态
                foreach ($yd_card as $yd){
                    $yunying = M('yunying');
                    $yidong = $yunying->find(2);
                    //接口需要数据
                    $uname = $yidong['username'];
                    $secret = $yidong['password'];
                    $tmp = time();
                    $card = $yd['card_id'];
                    $shuju =  $secret.'card'.$card.'tmp'.$tmp.'uname'.$uname.$secret;
                    echo $shuju;die();
                    $sign = md5($shuju);
                    $urls = $url_yd."?uname=".$uname."&secret=".$secret."&tmp=".$tmp."&card=".$card."&sign=".$sign."";
                    $xml = $this->RequestHttp($urls);
                    dump($xml);die();
                }
            }*/


        }
        /////
	    if($this->dbname == "daili"){
           $this->dbname = 'user';
        }
		$model = D($this->dbname);
		$map = $this->_search();
		if (($this->dbname) == "kahao") {
			$curre_user_id = $_SESSION['zs_admin']['userid'];
			$ausers = M('user')->where(array('id'=>$curre_user_id))->find();//当前用户
			if (!empty($map['state']) && empty($map['user_id'])) {
				if ($map['state'] == 1) {
					$map['state'] = 1;
				}else{
					$map['state'] = 0;
					// $map['user_id'] = array('neq','null');
				}
			}
			if (!empty($map['user_id']) && empty($map['state'])) {
				// $mapuser = M('user')->where(array('id'=>$map['user_id']))->find();//当前用户
				if ($ausers['dengji'] == 1) {
					$map['user_id'] = $map['user_id'];
				}

				if ($ausers['dengji'] == 2) {
					$map['san_id'] = $map['user_id'];
					unset($map['user_id']);
				}

				if ($ausers['dengji'] == 3) {
					$map['si_id'] = $map['user_id'];
					unset($map['user_id']);
				}
			}
		}
		$this->assign("map", $map);

		if (method_exists($this, '_filter')) {
			$this->_filter($map);
		}

		if (!empty($model)) {
			$this->_list($model, $map);
		}
		$this->display();
	}

	protected function _search($dbname='') {
		//生成查询条件
		
		$dbname = $dbname ? $dbname : $this->dbname;
		
		$model = D($dbname);
		$map = array();
			
		foreach ($model->getDbFields() as $key => $val) {
			if (isset($_REQUEST [$val]) && $_REQUEST [$val] != '') {
				if(in_array($val, array('name','account'))){//需要模糊查询的字段，可再添加，如title等
					$map [$val] = array('like','%'.$_REQUEST [$val].'%');
				}else{
					$map [$val] = $_REQUEST [$val];
				}
					
			}
		}
		return $map;
	}

	protected function mtReturn($status,$info,$navTabId='',$callbackType='closeCurrent',$forwardUrl='',$rel='', $type='') {
		// 保证AJAX返回后也能保存日志
		 
	    if (C('LOG_RECORD'))
		 {
		 	
		 	\Think\Log::save();
		 	
		 }
		
		 	
		 	
		$result = array();
		

		if($navTabId==''){
			$navTabId=$_REQUEST['navTabId'];
		}
		if($status=='200'){
			$this->sysLogs('', $info);
		}
		if($status=='201'){
			$status=200;
		}


		$result['statusCode'] = $status; // dwzjs
		$result['navTabId'] = $navTabId; // dwzjs
		$result['callbackType'] = $callbackType; // dwzjs
		$result['message'] = $info; // dwzjs
		$result['forwardUrl'] = $forwardUrl;
		$result['rel'] = $rel;
			
		if (empty($type))
		$type = C('DEFAULT_AJAX_RETURN');
		if (strtoupper($type) == 'JSON') {
			// 返回JSON数据格式到客户端 包含状态信息
			header("Content-Type:text/html; charset=utf-8");
			exit(json_encode($result));
		} elseif (strtoupper($type) == 'XML') {
			// 返回xml格式数据
			header("Content-Type:text/xml; charset=utf-8");
			exit(xml_encode($result));
		} elseif (strtoupper($type) == 'EVAL') {
			// 返回可执行的js脚本
			header("Content-Type:text/html; charset=utf-8");
			exit($data);
		} else {
			// TODO 增加其它格式
		}
	}
	public function insert() {
        set_time_limit(0);
        $curre_user_id = $_SESSION['zs_admin']['userid'];
        $users = M('user')->where(array('id'=>$curre_user_id))->find();//当前用户
		$model = D($this->dbname);
		if (false === $data= $model->create()) {

			$this->mtReturn(300, $model->getError());
		}
		$mobile = array_unique(explode(',', $data['mobile']));
		if (method_exists($this, '_before_insert')) {
			$data = $this->_before_insert($data);
		}
		//控制短信条数不能超过平台的总条数
		if ($this->dbname == 'user') {
			//总后台
			if ($users['dengji'] == 1) {
				$sms_count = M('user')->sum('smssum');//之前的用户的总短信条数
				// $sms_count = M('user')->where('parent_id=1')->sum('smssum');//之前的用户的总短信条数
				$platform = M('config')->where(array('name' =>'WEB_SMS_NUM'))->getField('value');//平台的总短信条数
				$all_sms_count = $_POST['smssum'] + $sms_count;
				if ($all_sms_count > $platform) {
					$end_num = $platform - $sms_count;//最多还可以添加的短信条数
					$this->mtReturn(300, '最多还可添加'.$end_num.'条');
				}
			}
			//二级给三级添加
			if ($users['dengji'] == 2) {
				if ($_POST['smssum'] > $users['smssum']) {
					$this->mtReturn(300, '不能超过上级的总条数,共'.$users['smssum'].'条');die;
				}
				$sheng_num = $users['smssum'] - $_POST['smssum'];
				M('user')->where(array('id'=>$users['id']))->setField('smssum',$sheng_num);
			}
			//三级给四级添加
			if ($users['dengji'] == 3) {
				if ($_POST['smssum'] > $users['smssum']) {
					$this->mtReturn(300, '不能超过上级的总条数,共'.$users['smssum'].'条');die;
				}
				$sheng_num = $users['smssum'] - $_POST['smssum'];
				M('user')->where(array('id'=>$users['id']))->setField('smssum',$sheng_num);
			}
				
		}
		

		// if(($this->dbname)=="article"){
		// 	if ($_POST['user_id'] == 0) {
		// 		$this->mtReturn(300, '用户必选!');die;
		// 	}
		// 	// $Art = M('article')->where(array('user_id'=>$_POST['user_id']))->find();
		// 	// if (!empty($Art)) {
		// 	// 	$this->mtReturn(300, '该用户已添加!');die;
		// 	// }
		// }
		if(($this->dbname)=="kahao"){
            foreach ($mobile as $key => $value) {
            	$ka = $model->where('mobile='.$value)->find();
            	if(!$ka){
            		$dataList[] = array('p_sn'=>$data['p_sn'],'mobile'=>$value,'time'=>$data['time']);
            	}
            }
            $list = $model->addAll($dataList);
		}else{	
			//保存当前数据对象
			$list = $model->add();
		}

		if ($list !== false) {
			if( method_exists($this, '_after_insert')){
				
				$this->_after_insert($list);
			}
			$this->mtReturn(200, '新增成功!');

		} else {
			$this->mtReturn(300, '新增失败!');
		}
	}
    public function add($html='') {
		
		$this->display($html);
	}


	public function edit($html='') {
		$curre_user_id = $_SESSION['zs_admin']['userid'];
		$model = D($this->dbname);
		$id = $_REQUEST [$model->getPk()];
		$vo = $model->getById($id);
		if ($this->dbname == 'codelist') {
			//用户
			$user_id = M('codelist')->where("id=".$id)->getField('user_id');
			$kauser = M('user')->field('id,nickname')->where(array('id'=>$user_id))->select();
		    $this->assign('kauser', $kauser);

		    //所有的目的码
		    $user_code = explode(',', $vo['code']);
			$content = M('article')->order('id desc')->select();
			foreach ($content as $key => $val) {
				foreach ($user_code as $k => $v) {
					if ($val['id'] == $v) {
						$content[$key]['user_id'] = $v;
					}
				}
			}
			// echo "<pre>";print_r($kauser);echo "</pre>";
			$this->assign('user_id', $user_id);
			$this->assign('content', $content);
		}
		$this->assign('vo', $vo);
		
		$this->display($html);
	}
	public function update() {
		$model = D($this->dbname);

		$curre_user_id = $_SESSION['zs_admin']['userid'];
        $users = M('user')->where(array('id'=>$curre_user_id))->find();//当前用户
		//控制短信条数不能超过平台的总条数
		if ($this->dbname == 'user') {
			//总后台
			if ($users['dengji'] == 1) {
				$sms_count = M('user')->sum('smssum');//之前的用户的总短信条数
				// $sms_count = M('user')->where('parent_id=1 and id <>'.$_POST['id'])->sum('smssum');//之前的用户的总短信条数
				$platform = M('config')->where(array('name' =>'WEB_SMS_NUM'))->getField('value');//平台的总短信条数
				$all_sms_count = $_POST['smssum'] + $sms_count;
				if ($all_sms_count > $platform) {
					$end_num = $platform - $sms_count;//最多还可以添加的短信条数
					$this->mtReturn(300, '最多还可添加'.$end_num.'条');
				}
			}
			//二级给三级添加
			if ($users['dengji'] == 2) {
				$tijiao_user = M('user')->where(array('id'=>$_POST['id']))->find();//当前提交数据的用户

				if ($tijiao_user['smssum'] > $_POST['smssum']) {
					//之前的大于现在提交的
					$tijiao_num = $tijiao_user['smssum'] - $_POST['smssum'];
					$tijiao_nums = $users['smssum'] + $tijiao_num;//这是给当前登录用户的,加回去
					M('user')->where(array('id'=>$users['id']))->setField('smssum',$tijiao_nums);
				}
				if ($tijiao_user['smssum'] < $_POST['smssum']) {
					if ($users['smssum'] > 0) {
						//之前的小于现在提交的
						$tijiao_num = $_POST['smssum'] - $tijiao_user['smssum'];
						//当前登录用户 - 提交过来中（加了的部分）
						$tijiao_nums = $users['smssum'] - $tijiao_num;//这是给当前登录用户的,减掉
						if ($tijiao_nums < 0) {//最后计算的这个数不能小于0
							$this->mtReturn(300, '最多可加'.$users['smssum'].'条');die;
						}else{
							M('user')->where(array('id'=>$users['id']))->setField('smssum',$tijiao_nums);
						}
					}else{
						if ($_POST['smssum'] > $users['smssum']) {
							$this->mtReturn(300, '不能超过总条数,当前总共'.$users['smssum'].'条');die;
						}
					}
					
				}
			}
			//三级给四级添加
			if ($users['dengji'] == 3) {
				$tijiao_user = M('user')->where(array('id'=>$_POST['id']))->find();//当前提交数据的用户

				if ($tijiao_user['smssum'] > $_POST['smssum']) {
					//之前的大于现在提交的
					$tijiao_num = $tijiao_user['smssum'] - $_POST['smssum'];
					$tijiao_nums = $users['smssum'] + $tijiao_num;//这是给当前登录用户的,加回去
					M('user')->where(array('id'=>$users['id']))->setField('smssum',$tijiao_nums);
				}
				if ($tijiao_user['smssum'] < $_POST['smssum']) {
					if ($users['smssum'] > 0) {
						//之前的小于现在提交的
						$tijiao_num = $_POST['smssum'] - $tijiao_user['smssum'];
						//当前登录用户 - 提交过来中（加了的部分）
						$tijiao_nums = $users['smssum'] - $tijiao_num;//这是给当前登录用户的,减掉
						if ($tijiao_nums < 0) {//最后计算的这个数不能小于0
							$this->mtReturn(300, '最多可加'.$users['smssum'].'条');die;
						}else{
							M('user')->where(array('id'=>$users['id']))->setField('smssum',$tijiao_nums);
						}
					}else{
						if ($_POST['smssum'] > $users['smssum']) {
							$this->mtReturn(300, '不能超过总条数,当前总共'.$users['smssum'].'条');die;
						}
					}
					
				}
			}
				
		}


		if (false === $data= $model->create()) {

			$this->mtReturn(300, $model->getError());
		}
		if (method_exists($this, '_before_update')) {
			$data = $this->_before_update($data);

		}
		if(($this->dbname)=="kahao"){
			$ka = $model->field('id,mobile')->where('mobile='.$data['mobile'])->find();
			if($ka && ($ka['id'] != $data['id'])){		
				$this->mtReturn(300, '该手机号码已经存在!');
				exit;
			}
		}	
		// 更新数据
		$list = $model->save();
		if (false !== $list) {
			if( method_exists($this, '_after_update')){
				$pk = $model->getPk ();
			    $this->_after_update($data[$pk]);
			}
            
			$this->mtReturn(200, '编辑成功!');
		} else {

			$this->mtReturn(300, '编辑失败!');
		}
	}


	function foreverdelete(){
		$model = D($this->dbname);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				if (method_exists($this, '_before_foreverdelete')) {
					$this->_before_foreverdelete($id);
				
						
					
				}
					
				
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					if (method_exists($this, '_after_foreverdelete')) {
						   $this->_after_foreverdelete($id);
                     }
					$this->mtReturn(200, '删除成功！','','forward',cookie('_currentUrl_'));

				} else {
					$this->mtReturn(300, '删除失败！');

				}
			} else {
				$this->mtReturn(300, '非法操作！');
					
			}
		}
		$this->forward ();
	}
	public function selectedDelete() {
		$model = D($this->dbname);
		if (!empty($model)) {
			$pk = $model->getPk();
			$id = $_REQUEST ['ids'];
			if (isset($id)) {
				if (method_exists($this, '_before_selectedDelete')) {
					$this->_before_selectedDelete($id);

				}
				
				$condition = array($pk => array('in', explode(',', $id)));
				if (false !== $model->where($condition)->delete()) {
					if (method_exists($this, '_after_selectedDelete')) {
						$this->_after_selectedDelete($id);

					}
					$this->mtReturn(200, '删除成功！','','forward',cookie('_currentUrl_'));

				} else {
					$this->mtReturn(300, '删除失败！');

				}
			} else {
				$this->mtReturn(300, '非法操作');

			}
		}
		$this->forward();
	}





	public function forbid() {

		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_REQUEST [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		$list = $model->where($condition)->setField('status',0);
		if ($list !== false) {
			$this->mtReturn(200, '禁用成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '禁用失败！');

		}

	}

	function resume() {
		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_GET [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		if (false !== $model->where($condition)->setField('status',1)) {

			$this->mtReturn(200, '恢复成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '恢复失败！');

		}
	}
	public function willhidden() {

		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_REQUEST [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		$list = $model->where($condition)->setField('show',0);
		if ($list !== false) {
			$this->mtReturn(200, '隐藏成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '隐藏失败！');

		}

	}

	function willshow() {
		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_GET [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		if (false !== $model->where($condition)->setField('show',1)) {

			$this->mtReturn(200, '显示成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '显示失败！');

		}
	}
	
	



	function sysLogs($opname='未知', $message='未知') {
		$syslogs = D("Syslogs");
		$data = array();
		$ip = get_client_ip();
		$data['modulename'] = getmodulename();
		$data['actionname'] = getactionname();
		$data['opname'] = $opname;
		$data['message'] = $message;
		$data['username'] = session('loginUserName') . "(" . session('login_account') . ")";
		$data['userid'] = $_SESSION[C('USER_AUTH_KEY')];
		$data['userip'] = $ip;
		$data['create_time'] = time();
		$result = $syslogs->add($data);
	}

	/*
	 * 以下的函数尚未启用，主要用于将列表中的数据删除时并非直接删除，而是先放入回收站
	 * 如果需要恢复数据，可以点击回收站恢复
	 * 也可以在回收站彻底删除数据
	 *
	 *
	 * */
	public function pass() {
		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_GET [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		if (false !== $model->where($condition)->setField('status',1)) {

			$this->mtReturn(200, '批准成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '批准失败！');

		}
	}

	public function recycle() {
		$model = D($this->dbname);
		$pk = $model->getPk();
		$id = $_GET [$pk];
		$condition = array($pk => array('in', explode(',', $id)));
		if (false !== $model->where($condition)->setField('status',0)) {


			$this->mtReturn(200, '还原成功！','','forward',cookie('_currentUrl_'));

		} else {
			$this->mtReturn(300, '还原失败！');

		}
	}

	public function recycleBin() {
		$map = $this->_search();
		$map ['status'] = - 1;
		$model = D($this->dbname);
		if (!empty($model)) {
			$this->_list($model, $map);
		}
		$this->display();
	}

	public function delete() {
		$model = D($this->dbname);
		if (!empty($model)) {
			$pk = $model->getPk();
			$id = $_REQUEST [$pk];
			if (isset($id)) {
				
			    if (method_exists($this, '_before_delete')) {
					$this->_before_delete($id);
			   
				}
				
				
				
				$condition = array($pk => array('in', explode(',', $id)));
				$list = $model->where($condition)->setField('status', - 1);
				if ($list !== false) {

				    if (method_exists($this, '_after_delete')) {
						$this->_after_delete($id);

					}
					$this->mtReturn(200, '删除成功！','','forward',cookie('_currentUrl_'));

				} else {
					$this->mtReturn(300, '删除失败！');

				}
			} else {
				$this->mtReturn(300, '非法操作');

			}
		}
	}

	public function clear() {//彻底删除回收站
		$model = D($this->dbname);
		if (!empty($model)) {
			if (false !== $model->where('status=-1')->delete()) {

				$this->mtReturn(200, '彻底删除成功！','','forward',cookie('_currentUrl_'));

			} else {
				$this->mtReturn(300, '彻底删除失败！');

			}
		}
		$this->forward();
	}
}
?>